//
//  M13HttpRequest.m
//  ELife
//
//  Created by  丰 on 11-5-13.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "M13HttpRequest.h"
#import "ASIFormDataRequest.h"
#import "GTMBase64.h"

@implementation M13HttpRequest

-(id)init
{
	if (self = [super init]) {
		
	}
	netWorkQueueDic = [[NSMutableDictionary dictionary] retain];
	
	return self;
}

- (void)dealloc
{
    [netWorkQueueDic release];
}


- (void)openUrlByReq:(ASIHTTPRequest *)req target:(id)target
{
    NSMutableString* retStr = [[NSMutableString alloc]  initWithData:[req postBody] encoding:NSUTF8StringEncoding];

    NSLog(@"retStr:----------%@", retStr);
    [netWorkQueueDic setValue:target forKey:[NSString stringWithFormat:@"%@%@", [[req url] absoluteString], retStr]];
    //[netWorkQueueDic setValue:target forKey:[req url]];
    [retStr release];
    if(![req queue]) 
	{ 
		[req setQueue:[[[NSOperationQueue alloc]init]autorelease]];
	} 
	
	[req setDelegate:self];
	[[req queue]addOperation:req];
}

- (void)openUrl:(NSDictionary *)urlDic target:(id)target
{
    ASIHTTPRequest *req = [ASIHTTPRequest requestWithURL:[urlDic objectForKey:@"url"]];
    [req setRequestMethod1:[urlDic objectForKey:@"requestMethod"]];
    //NSLog(@"requestMethod＝%@", [req requestMethod1]);
    [self openUrlByReq:req target:target];
}



- (void)openUrl:(NSDictionary *)urlDic postParam:(NSDictionary *)param target:(id)target
{
    
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[urlDic objectForKey:@"url"]];
    [request setRequestMethod1:[urlDic objectForKey:@"requestMethod"]];
    [request setUseCookiePersistence:YES];
    //NSLog(@"%@", [request requestMethod1]);
    
    NSLog(@"url=%@", [urlDic objectForKey:@"url"]);
    NSLog(@"keys=%@", param);

    NSEnumerator *keys = [param keyEnumerator];
    id key;
    while (key = [keys nextObject]) {
        NSString *value = [param objectForKey:key];

        [request setPostValue:value forKey:key];
    }
    [request buildPostBody];
    NSError *error = [request error];
    if (!error) {
        NSString *response = [request responseString];
    }
    [request setRequestMethod:@"POST"];
    [self openUrlByReq:request target:target];
}



- (void)requestFailed:(ASIHTTPRequest *)request
{
    if (request == nil) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提醒" message:@"没有可用的网络连接" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
        [alertView release];
        return;
    }
	NSData* data = [request responseData];
    NSMutableString* retStr = [[NSMutableString alloc]  initWithData:[request postBody] encoding:NSUTF8StringEncoding];
    NSString* key = [NSString stringWithFormat:@"%@%@", [[request url] absoluteString], retStr];
	if(![[netWorkQueueDic objectForKey:key] isKindOfClass:[self class]])
	{
		UIViewController* cont = [netWorkQueueDic objectForKey:key];
        if ([cont respondsToSelector:@selector(iRequestFailed)] == YES) {
            [cont iRequestFailed];
        }
	}
	[netWorkQueueDic removeObjectForKey:key];
    
    [retStr release];
    
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
    NSData* data = [request responseData];
//    NSLog(@"%i", [data length]);

//    NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[[request url] absoluteURL]];
//    NSLog(@"cookie = %@", cookies);
    NSMutableString* retStr = [[NSMutableString alloc]  initWithData:[request postBody] encoding:NSUTF8StringEncoding];
    NSString* key = [NSString stringWithFormat:@"%@%@", [[request url] absoluteString], retStr];

    //NSLog(@"%@", [request requestMethod1]);
    
    SEL print_sel = NSSelectorFromString([request requestMethod1]);
    IMP imp = [[netWorkQueueDic objectForKey:key] methodForSelector:print_sel];
    imp([netWorkQueueDic objectForKey:key], print_sel, data);
	
	[netWorkQueueDic removeObjectForKey:key];
    
}

-(void)getImageDataByUrl:(NSString *)urlStr forUIImage:(UIImage *)img delegate:(id)target
{
    NSURL *url = [NSURL URLWithString:urlStr];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    
    if (![request queue]) {
        [request setQueue:[[[NSOperationQueue alloc] init] autorelease]];
    }

    [request setDelegate:self];
    [request setDidFinishSelector:@selector(imgRequestFinished:)];
    [request setDidFailSelector:@selector(imgRequestFail:)];
    [[request queue] addOperation:request]; //queue is an NSOperationQueue
    
    // 图片加入消费者队列 url做key
    NSArray *arr = [NSArray arrayWithObjects:target, img, nil];
    [netWorkQueueDic setObject:arr forKey:urlStr];
    NSLog(@"add image download:%@", urlStr);
    NSLog(@"networkQueueDic:%@", netWorkQueueDic);
}

-(void)imgRequestFinished:(ASIHTTPRequest *)request
{
    NSString *urlStr = [[request url] absoluteString];
    
    NSLog(@"img download finished:%@", urlStr);
    NSLog(@"networkQueueDic:%@", netWorkQueueDic);

    NSArray *arr = (NSArray *)[netWorkQueueDic objectForKey:urlStr];
    id target = [arr objectAtIndex:0];
    
    UIImage *img = nil;
    if ([arr count] > 1) {
        img = [arr objectAtIndex:1];

    }
    
    
    NSData *imgData = [request responseData];
    
    [netWorkQueueDic removeObjectForKey:urlStr];
    
    if ([target respondsToSelector:@selector(refreshWithImageData:)] == YES) {
        [target refreshWithImageData:imgData];
    } else if ([target respondsToSelector:@selector(refreshImage)] == YES) {
        [img initWithData:imgData];
        [target refreshImage];
    }
}

-(void)imgRequestFail:(ASIHTTPRequest *)request
{
    NSString *urlStr = [[request url] absoluteString];
    [netWorkQueueDic removeObjectForKey:urlStr];
}

@end
